package com.zxy.supplier_system.server.service

import com.zxy.supplier_system.server.controller.MarketShoppingGuideSalaryPlanDetailPreviewController
import com.zxy.supplier_system.server.entity.sortByCondition
import com.zxy.supplier_system.server.repository.MarketSaleDocumentRepository
import com.zxy.supplier_system.server.repository.MarketShoppingGuideSalaryRuleRepository
import com.zxy.supplier_system.server.service.MarketShoppingGuideSalaryDocumentService.Companion.computeRuleSaleItemMap
import com.zxy.supplier_system.server.utils.orElse404
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Transactional

@Service
class MarketShoppingGuideSalaryPlanDetailPreviewService(
    private val marketSaleDocumentRepository: MarketSaleDocumentRepository,
    private val systemServiceService: SystemServiceService,
    private val marketShoppingGuideSalaryRuleRepository: MarketShoppingGuideSalaryRuleRepository,
) {

    @Transactional(readOnly = true)
    fun previewDetail(
        ruleId: Int,
        month: Int,
        year: Int,
    ): List<MarketShoppingGuideSalaryPlanDetailPreviewController.MarketShoppingGuideSalaryPlanRuleDetailPreviewResponse> {
        val currentSystemService = systemServiceService.getCurrentSystemService()
        val rule =
            this.marketShoppingGuideSalaryRuleRepository.findByIdAndPlan_Market_SystemService(
                ruleId,
                currentSystemService
            ).orElse404()
        val marketShoppingGuideSalaryPlan = rule.plan

        val documents =
            marketSaleDocumentRepository.findAllByAccount_Market_IdAndAccount_Market_SystemServiceAndYearAndMonth(
                marketShoppingGuideSalaryPlan.market.id,
                currentSystemService,
                year,
                month
            )
        val sortedRules =
            marketShoppingGuideSalaryPlan.rules.sortByCondition().filter { it.commissionPercentage != null }
        val goodsList = documents.flatMap { it.goodsList }
        val ruleSaleItemMap =
            computeRuleSaleItemMap(goodsList, sortedRules.subList(0, sortedRules.indexOfFirst { it.id == ruleId } + 1))

        return ruleSaleItemMap[rule]?.map {
            MarketShoppingGuideSalaryPlanDetailPreviewController.MarketShoppingGuideSalaryPlanRuleDetailPreviewResponse(
                it.goods.barcode,
                it.goods.id,
                it.goods.name,
                it.amount,
                it.totalFee
            )
        } ?: emptyList()
    }

}
